/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ships.core.icc.io;

import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 *
 * @author fqhuy
 */
public class IccFileInputStream extends IccInputStream {

    protected RandomAccessFile raf;


    public IccFileInputStream(File f)
            throws FileNotFoundException, IOException {
        this(f == null ? null : new RandomAccessFile(f, "r"));
    }

    public IccFileInputStream(RandomAccessFile raf) {
        if (raf == null) {
            throw new IllegalArgumentException("raf == null!");
        }
        this.raf = raf;
        /*
        disposerRecord = new CloseableDisposerRecord(raf);
        if (getClass() == IccFileInputStream.class) {
        disposerReferent = new Object();
        Disposer.addRecord(disposerReferent, disposerRecord);
        } else {
        disposerReferent = new StreamFinalizer(this);
        }
*/
    }

    public int read() throws IOException {
        checkClosed();
        bitOffset = 0;
        int val = raf.read();
        if (val != -1) {
            ++streamPos;
        }
        return val;
    }

    public int read(byte[] b, int off, int len) throws IOException {
        checkClosed();
        bitOffset = 0;
        int nbytes = raf.read(b, off, len);
        if (nbytes != -1) {
            streamPos += nbytes;
        }
        return nbytes;
    }

    @Override
    public long length() {
        try {
            checkClosed();
            return raf.length();
        } catch (IOException e) {
            return -1L;
        }
    }

    @Override
    public void seek(long pos) throws IOException {
        checkClosed();
        if (pos < flushedPos) {
            throw new IndexOutOfBoundsException("pos < flushedPos!");
        }
        bitOffset = 0;
        raf.seek(pos);
        streamPos = raf.getFilePointer();
    }

    @Override
    public void close() throws IOException {
        super.close();
        //disposerRecord.dispose(); // this closes the RandomAccessFile
        raf = null;
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();

    }

}
